package com.example.datasourcetest.util;

import com.example.datasourcetest.enums.DataSourceType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(-1)
@Slf4j
public class DataSourcePartAspect {
    /**
     * mapper 查询操作默认使用从库
     * ..表示包下的目录和子目录
     */
    @Before("execution(* com.example.datasourcetest.service..*.select*(..)) || execution(* com.example.datasourcetest.service..*.get*(..))|| execution(* com.example.datasourcetest.service..*.query*(..))")
    public void setReadDataSourceType() {
        log.info("当前数据源：{}",DynamicDataSourceHolder.getDataSouce());
        DynamicDataSourceHolder.putDataSource(DataSourceType.SLAVE);
        log.info("数据库执行读操作，dataSource 切换到：{}",DataSourceType.SLAVE.getName());
    }

    /**
     * mapper 修改删除操作默认使用主库库
     */
    @Before("execution(* com.example.datasourcetest.service..*.insert*(..)) || execution(* com.example.datasourcetest.service..*.update*(..)) || execution(* com.example.datasourcetest.service..*.delete*(..))")
    public void setWriteDataSourceType() {
        log.info("当前数据源：{}",DynamicDataSourceHolder.getDataSouce());
        DynamicDataSourceHolder.putDataSource(DataSourceType.MASTER);
        log.info("数据库执行写操作，dataSource 切换到：{}",DataSourceType.MASTER.getName());
    }

    /**
     * 完成后释放
     * @param point
     */
    @After("execution(* com..service..*.select*(..)) || execution(* com..service..*.get*(..))|| execution(* com..service..*.query*(..))")
    public void afterSwitchDSCheck(JoinPoint point){
        DynamicDataSourceHolder.remove();
    }

    @After("execution(* com..service..*.insert*(..)) || execution(* com..service..*.update*(..)) || execution(* com..service..*.delete*(..))")
    public void afterSwitchDS(JoinPoint point){
        DynamicDataSourceHolder.remove();
    }

}
